'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 在线人数统计
 * @author agl
 */

var _ = require('lodash');
var onlineUserCountModel = require('../models/onlineUserCountModel');

var online_info = {};

/**
 * 增加在线人数
 * @param {[type]} channel_id [description]
 */
exports.addOnlineUser = function (channel_id, cb) {
    if (!channel_id) {
        console.error('call onlineUserCountService.addOnlineUser(channel_id): channel_id can not be null');
        return;
    }
    onlineUserCountModel.findByChannel(channel_id, function (err, model) {
        model.user_count++;
        model.save(function (err, model) {
            if (!!cb) {
                cb(null);
            }
        });
    });
};

/**
 * 减少在线人数
 * @param {[type]} channel_id [description]
 */
exports.subOnlineUser = function (channel_id, cb) {
    if (!channel_id) {
        console.error('call onlineUserCountService.subOnlineUser(channel_id): channel_id can not be null');
        return;
    }
    onlineUserCountModel.findByChannel(channel_id, function (err, model) {
        model.user_count--;
        if (model.user_count > 0) {
            model.save(function (err, model) {
                if (!!cb) {
                    cb(null);
                }
            });
        } else {
            onlineUserCountModel.removeByChannel(channel_id, cb);
        }
    });
};

/**
 * 查询在线人数信息
 * @param {[type]} channel_id [description]
 */
exports.getOnlineInfo = function (cb) {
    var online_user_count = {};
    onlineUserCountModel.findAll(function (err, model_list) {
        _.forEach(model_list, function (model) {
            online_user_count[model.channel_id] = model.user_count;
        });
        cb(null, online_user_count);
    });
};

/**
 * 清除在线人数信息
 * @param {[type]} channel_id [description]
 */
exports.clearOnlineInfo = function (cb) {
    onlineUserCountModel.clearAll(cb);
};
